package com.yhn.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hospital.common.base.PageResult;
import com.hospital.common.base.Result;
import com.hospital.common.dto.audit.module.SaveLogDto;
import com.hospital.common.dto.section.PostQueryReqDto;
import com.hospital.common.dto.section.SectionCreateReqDto;
import com.hospital.common.dto.section.SectionQueryReqDto;
import com.hospital.common.dto.section.SectionUpdateReqDto;
import com.hospital.common.pojo.TPostMeta;
import com.hospital.common.pojo.TSection;
import com.hospital.common.pojo.TUser;
import com.hospital.common.vo.section.module.SectionVo;
import com.yhn.feign.AuditLogFeign;
import com.yhn.mapper.SectionMapper;
import com.yhn.mapper.UserMapper;
import com.yhn.service.SectionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class SectionServiceImpl implements SectionService {
    @Autowired
    private SectionMapper sectionMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AuditLogFeign auditLogFeign;

    @Override
    public TSection createSection(Long operatorUserId, SectionCreateReqDto req) {
        // 检查操作人权限：只有管理员可以创建板块
        int permissionCount = sectionMapper.checkAdminPermission(operatorUserId, 0L);
        if (permissionCount == 0) {
            // 无权限，返回特殊标识
            return new TSection();
        }
        // 简单校验：名称唯一
        if (sectionMapper.findByName(req.getName()) != null) {
            // 重名时返回空，由上层统一包装业务返回
            return null;
        }
        TSection entity = new TSection();
        entity.setAdminId(operatorUserId);
        entity.setName(req.getName());
        entity.setIntroduction(req.getIntroduction());
        // 使用前端传来的Logo URL，如果没有则使用默认图片
        entity.setLogoUrl(req.getLogoUrl() != null && !req.getLogoUrl().trim().isEmpty()
                ? req.getLogoUrl() : "default-logo.png");
        entity.setNotice(req.getNotice());
        sectionMapper.insert(entity);

        // 记录操作日志
        saveAuditLog(operatorUserId, entity.getId(), "新增");

        return entity;
    }

    @Override
    public TSection updateSection(Long operatorUserId, SectionUpdateReqDto req) {
        // 检查操作人权限：只有管理员可以编辑板块
        int permissionCount = sectionMapper.checkAdminPermission(operatorUserId, 0L);
        if (permissionCount == 0) {
            // 无权限，返回特殊标识
            return new TSection();
        }
        // 名称存在且不是当前这个id，则认为重名
        if (req.getName() != null) {
            TSection existed = sectionMapper.findByName(req.getName());
            if (existed != null && !existed.getId().equals(req.getId())) {
                return null;
            }
        }
        TSection entity = new TSection();
        entity.setId(req.getId());
        entity.setName(req.getName());
        entity.setIntroduction(req.getIntroduction());
        entity.setLogoUrl(req.getLogoUrl());
        // 由 XML set 节点选择性更新
        sectionMapper.updateById(entity);

        // 记录操作日志
        saveAuditLog(operatorUserId, entity.getId(), "修改");

        return entity;
    }


    @Override
    public Integer deleteSection(Long operatorUserId, Long sectionId) {
        // 检查操作人权限：只有管理员可以删除板块
        int permissionCount = sectionMapper.checkAdminPermission(operatorUserId, 0L);
        if (permissionCount == 0) {
            // 无权限，返回 -1
            return -1;
        }
        // 检查板块是否存在
        TSection section = sectionMapper.findById(sectionId);
        if (section == null) {
            return null; // 板块不存在
        }

        // 检查是否有帖子
        int postCount = sectionMapper.countPostsBySectionId(sectionId);
        if (postCount > 0) {
            return 0; // 有帖子，不能删除
        }

        // 执行逻辑删除，记录删除者ID
        sectionMapper.deleteById(sectionId, operatorUserId);

        // 记录操作日志
        saveAuditLog(operatorUserId, sectionId, "删除");

        return 1; // 删除成功
    }

    @Override
    public Integer assignModerator(Long operatorUserId, Long sectionId, Long doctorUserId) {
        // 检查操作人权限：只有管理员可以分配版主
        int permissionCount = sectionMapper.checkAdminPermission(operatorUserId, 0L);
        if (permissionCount == 0) {
            // 无权限，返回 -1
            return -1;
        }

        // 检查板块是否存在
        TSection section = sectionMapper.findById(sectionId);
        if (section == null) {
            return null; // 板块不存在
        }

        // 检查医生用户是否存在且角色为医生
        TUser user = userMapper.findById(doctorUserId);
        if (user == null || user.getRole() != 1) {
            return 0; // 医生不存在或角色不对
        }

        // 检查该医生是否已经是其他板块的版主（一对一约束）
        List<Long> assignedModeratorIds = sectionMapper.selectAssignedModeratorIds();
        if (assignedModeratorIds.contains(doctorUserId)) {
            return -2; // 该医生已经是其他板块的版主
        }

        // 更新板块的版主ID
        sectionMapper.updateModeratorId(sectionId, doctorUserId);
        sectionMapper.addAdmin(sectionId, doctorUserId);
        return 1; // 分配成功
    }

    @Override
    public TSection getSectionNotice(Long sectionId) {
        return sectionMapper.findById(sectionId);
    }

    @Override
    public Boolean updateSectionNotice(Long operatorUserId, Long sectionId, String notice) {
        // 检查板块是否存在
        TSection section = sectionMapper.findById(sectionId);
        if (section == null) {
            return null; // 板块不存在
        }

        // 检查操作人权限：从 t_admin 表查询
        int permissionCount = sectionMapper.checkAdminPermission(operatorUserId, sectionId);
        if (permissionCount == 0) {
            return false; // 无权限
        }

        // 更新公告
        sectionMapper.updateNotice(sectionId, notice);
        return true; // 更新成功
    }

    @Override
    @Transactional
    public Boolean setPostTop(Long operatorUserId, Long postId, Integer isTop) {
        // 获取帖子所属板块ID
        Long sectionId = sectionMapper.getPostSectionId(postId);
        if (sectionId == null) {
            return null; // 帖子不存在
        }

        // 检查权限：管理员或版主
        if (!hasPostManagementPermission(operatorUserId, sectionId)) {
            return false; // 无权限
        }

        // 更新置顶状态
        int affectedRows = sectionMapper.updatePostTopStatus(postId, isTop);
        return affectedRows > 0;
    }

    @Override
    @Transactional
    public Boolean setPostPinned(Long operatorUserId, Long postId, Integer isPinned) {
        // 获取帖子所属板块ID
        Long sectionId = sectionMapper.getPostSectionId(postId);
        if (sectionId == null) {
            return null; // 帖子不存在
        }

        // 检查权限：管理员或版主
        if (!hasPostManagementPermission(operatorUserId, sectionId)) {
            return false; // 无权限
        }

        // 更新加精状态
        int affectedRows = sectionMapper.updatePostPinnedStatus(postId, isPinned);
        return affectedRows > 0;
    }


    /**
     * 检查用户是否有帖子管理权限
     * @param operatorUserId 操作人用户ID
     * @param sectionId 板块ID
     * @return true有权限，false无权限
     */
    private boolean hasPostManagementPermission(Long operatorUserId, Long sectionId) {
        // 检查是否为管理员（可以管理所有帖子）
        int adminPermission = sectionMapper.checkAdminPermission(operatorUserId, 0L);
        if (adminPermission > 0) {
            return true;
        }

        // 检查是否为该板块的版主（只能管理自己板块的帖子）
        int moderatorPermission = sectionMapper.checkModeratorPermission(operatorUserId, sectionId);
        return moderatorPermission > 0;
    }

    @Override
    public Integer getAllSectionsCount() {
        return sectionMapper.countAllSections();
    }

    @Override
    public List<SectionVo> findAllSection() {
        try {
            return sectionMapper.findAll();
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

    @Override
    public SectionVo findSectionById(Long id) {
        if (id == null) {
            return null;
        }
        try {
            return sectionMapper.findSectionById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public List<Long> findSectionIdsByModeratorId(Long moderatorId) {
        if (moderatorId == null) {
            return new ArrayList<>();
        }
        try {
            return sectionMapper.findSectionIdsByModeratorId(moderatorId);
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

    @Override
    public PageResult<SectionVo> findAllSection(Integer pageNum, Integer pageSize) {
        if (pageNum == null || pageNum < 1) {
            pageNum = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }

        try {
            // 开启分页
            PageHelper.startPage(pageNum, pageSize);

            // 查询数据
            List<SectionVo> sections = sectionMapper.findAll();

            // 获取分页信息
            PageInfo<SectionVo> pageInfo = new PageInfo<>(sections);

            // 构造PageResult
            PageResult<SectionVo> pageResult = new PageResult<>();
            pageResult.setTotal(pageInfo.getTotal());
            pageResult.setRows(pageInfo.getList());

            return pageResult;
        } catch (Exception e) {
            e.printStackTrace();
            PageResult<SectionVo> pageResult = new PageResult<>();
            pageResult.setTotal(0L);
            pageResult.setRows(new ArrayList<>());
            return pageResult;
        }
    }

    /**
     * 保存审核日志
     * @param operatorUserId 操作人用户ID
     * @param sectionId 板块ID
     * @param operationType 操作类型 (add/update/delete)
     */
    private void saveAuditLog(Long operatorUserId, Long sectionId, String operationType) {
        try {
            SaveLogDto saveLogDto = new SaveLogDto();
            saveLogDto.setAdminId(operatorUserId);
            saveLogDto.setSectionId(sectionId);
            saveLogDto.setUrl(operationType);

            Result<?> result = auditLogFeign.saveSectionLog(saveLogDto);
            // 静默降级：不检查返回、不打印日志
        } catch (Exception e) {
            // 静默降级：不打印异常
        }
    }

    @Override
    public PageInfo<SectionVo> getSections(SectionQueryReqDto req) {
        // 开启分页
        PageHelper.startPage(req.getPageNum(), req.getPageSize());

        // 调用Mapper查询
        List<SectionVo> sections = sectionMapper.selectSectionsByName(req.getName());

        // 返回分页信息
        return new PageInfo<>(sections);
    }

    @Override
    public PageInfo<TPostMeta> getPosts(PostQueryReqDto req) {
        // 开启分页
        PageHelper.startPage(req.getPageNum(), req.getPageSize());

        // 调用Mapper查询
        List<TPostMeta> posts = sectionMapper.selectPostsByCondition(req);

        // 返回分页信息
        return new PageInfo<>(posts);
    }

    @Override
    public List<Map<String, Object>> getDoctors() {
        // 查询所有医生用户（角色：1医生）
        List<TUser> doctors = userMapper.selectUsersByRole(1);

        // 查询已经分配了版主的医生ID列表
        List<Long> assignedModeratorIds = sectionMapper.selectAssignedModeratorIds();

        List<Map<String, Object>> doctorList = new ArrayList<>();
        for (TUser doctor : doctors) {
            // 排除已经分配了版主的医生
            if (assignedModeratorIds.contains(doctor.getId())) {
                continue;
            }

            Map<String, Object> doctorMap = new HashMap<>();
            doctorMap.put("id", doctor.getId());
            doctorMap.put("name", doctor.getName() != null ? doctor.getName() : doctor.getAccount());
            doctorMap.put("username", doctor.getAccount());
            doctorList.add(doctorMap);
        }

        return doctorList;
    }

}
